<template>
  <ZForm
    :fields="passwordFields"
    :schema="passwordSchema"
    :initial-values="formData"
    @submit="onSubmit"
  >
    <div class="flex gap-1 justify-end">
      <ZButton
        class="mt-2"
        color="secondary"
        icon-class="icon-[mdi--restart] size-6"
        type="reset"
      >
        重 置
      </ZButton>
      <ZButton
        class="mt-2"
        color="primary"
        icon-class="icon-[mdi--content-save] size-6"
        type="submit"
        :loading="isFetching"
      >
        更 改
      </ZButton>
    </div>
  </ZForm>
</template>

<script setup lang="ts">
import { z } from "zod";
import type { FormFields } from "@/components/form/types";
import ZForm from "@/components/form/ZForm.vue";
import ZButton from "@/components/ui/ZButton.vue";

import { useMutation } from "@pinia/colada";
import type { SubmissionContext } from "vee-validate";
import { changePassword } from "@/apis/user";

const passwordSchema = z
  .object({
    oldPassword: z.string().min(6, "密码至少6位").max(16, "密码最多16位"),
    password: z.string().min(6, "密码至少6位").max(16, "密码最多16位"),
    confirmPassword: z.string().min(6, "密码至少6位").max(16, "密码最多16位"),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "两次密码不一致",
    path: ["confirmPassword"],
  });

const passwordFields: FormFields = [
  {
    name: "oldPassword",
    label: "旧密码",
    type: "password",
    inputAttributes: {
      placeholder: "请输入旧密码",
      title: "旧密码，至少6位，最多20位！",
    },
  },
  {
    name: "password",
    label: "新密码",
    type: "password",
    inputAttributes: {
      placeholder: "请输入新密码",
    },
  },
  {
    name: "confirmPassword",
    label: "确认密码",
    type: "password",
    inputAttributes: {
      placeholder: "请再次输入新密码",
    },
  },
];

const formData = {
  oldPassword: "",
  password: "",
  confirmPassword: "",
};

const { isLoading: isFetching, mutateAsync } = useMutation({
  mutation: changePassword,
});

async function onSubmit(
  values: z.infer<typeof passwordSchema>,
  { resetForm, setErrors }: SubmissionContext
) {
  const data = await mutateAsync(values);

  if (data?.success) {
    resetForm();
  } else {
    if (data?.errors) setErrors(data.errors);
  }
}
</script>
